﻿using MTQ.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace MTQ.BLL
{
    public class EmailService
    {
        public static string ServerPath = "";
        public static void SendEmail()
        {
            M_EmailSendService ess = new M_EmailSendService();
            List<M_EmailSend> list = ess.LoadEntities(x => x.ES_SendStatus == 0).ToList();

            foreach (M_EmailSend item in list)
            {
                try
                {
                    if (SendMailUse(item.ES_Receiver, item.ES_Title, item.ES_Content, item.ES_Attachment))
                    {
                        item.ES_SendStatus = 1;
                        item.ES_SendTime = System.DateTime.Now;
                        ess.UpdateEntity(item);
                    }
                }
                catch (Exception ex)
                {
                    Common.LogManager.WriteLog("SendEmail异常", ex);
                }
            }
        }

        /// <summary>
        /// SmtpClient 只能发送25端口邮件 ，无法发送465端口邮件 ，阿里云25端口号已经被封
        /// </summary>
        /// <param name="strto"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static bool SendMailUse(string strto, string subject, string body, string attachment)
        {
           
            string host = "xxx@xxx.com";// 邮件服务器smtp.163.com表示网易邮箱服务器    
            string userName = "xxxx@xxxx.com";//"mingyong.gao@formeld.com";// 发送端账号   
            string password = "xxxx";// 发送端密码(这个客户端重置后的密码)  qima12345@
            int port = 587;


            SmtpClient client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式    
            client.Host = host;//邮件服务器
            client.Port = port;//改用587端口
            client.UseDefaultCredentials = true;
            client.Credentials = new System.Net.NetworkCredential(userName, password);//用户名、密码
            client.EnableSsl = true;



            //////////////////////////////////////
            string strfrom = userName;
            //string strto = "simon.meng@qimajqr.com";
            // string strcc = "2605625733@qq.com";//抄送
            //string subject = "这是测试邮件标题5";//邮件的主题             
            //string body = "测试邮件内容5";//发送的邮件正文  

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.From = new MailAddress(strfrom, "FormelD Server");


            foreach (var item in strto.Split(';').ToList()) {
                if (string.IsNullOrEmpty(item)) {
                    continue;
                }
                msg.To.Add(item);
            }

           
            //msg.CC.Add(strcc);

            msg.Subject = subject;//邮件标题   
            msg.Body = body;//邮件内容   
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码   
            msg.IsBodyHtml = true;//是否是HTML邮件   
            msg.Priority = MailPriority.Normal;//邮件优先级   
            //Attachment amen = new Attachment(System.Web.HttpContext.Current.Server.MapPath(文件路径));
            //msg.Attachments.Add(amen);
            foreach (var str in attachment.Split(';').ToList())
            {
                //Attachment amen = new Attachment(ServerPath + str);

                //System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment(
                //            ServerPath + str, System.Net.Mime.MediaTypeNames.Application.Octet);

                ////MIME协议下的一个对象，用以设置附件的创建时间，修改时间以及读取时间
                //System.Net.Mime.ContentDisposition disposition = myAttachment.ContentDisposition;
                //disposition.CreationDate = System.IO.File.GetCreationTime(ServerPath + str);
                //disposition.ModificationDate = System.IO.File.GetLastWriteTime(ServerPath + str);
                //disposition.ReadDate = System.IO.File.GetLastAccessTime(ServerPath + str);

               
                //msg.Attachments.Add(new Attachment(ServerPath + str));
               // msg.Attachments.Add(myAttachment);
            }


            try
            {
                client.Send(msg);
                return true;
                //Console.WriteLine("发送成功");
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                Common.LogManager.WriteLog("SendEmail失败", ex);
                return false;
                //Console.WriteLine(ex.Message, "发送邮件出错");
            }
        }



        /// <summary>
        /// SmtpMail 
        /// </summary>
        /// <param name="strto"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static bool SendMailUseWeb(string strto, string subject, string body, string attachment)
        {
            string host = "xxx@xxx.com";// 邮件服务器smtp.163.com表示网易邮箱服务器    
            string userName = "xxxx@xxxx.com";//"@qqq.com";// 发送端账号   
            string password = "xxxx";// 发送端密码(这个客户端重置后的密码)  
           

            System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
            mail.To = strto;
            mail.From = userName;
            mail.Subject = subject;
            mail.BodyFormat = System.Web.Mail.MailFormat.Html;
            mail.Body = body;

            //foreach (var str in attachment.Split(';').ToList())
            //{
            //    System.Web.Mail.MailAttachment ma = new System.Web.Mail.MailAttachment(ServerPath + str);
            //    mail.Attachments.Add(ma);
            //}


            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //身份验证  
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", mail.From); //邮箱登录账号，这里跟前面的发送账号一样就行  
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); //这个密码要注意：如果是一般账号，要用授权码；企业账号用登录密码  
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 587);//端口  
                                                                                                  //
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//SSL加密  
            System.Web.Mail.SmtpMail.SmtpServer = host;    //企业账号用smtp.exmail.qq.com  
            try
            {
                System.Web.Mail.SmtpMail.Send(mail);
                return true;
                //Console.WriteLine("发送成功");
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                Common.LogManager.WriteLog("SendEmail失败", ex);
                return false;
                //Console.WriteLine(ex.Message, "发送邮件出错");
            }
        }



    }
}
